package com.xxl.rpc.admin.test;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Foo {


    Lock lock = new ReentrantLock();
    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();
    Condition condition3 = lock.newCondition();
    int num=1;
    public Foo() {

    }

    public static void main(String[] args) throws InterruptedException {
        Foo foo = new Foo();
        foo.first(new Runnable() {
            @Override
            public void run() {
                System.out.println(1);
            }
        });
        foo.second(new Runnable() {
            @Override
            public void run() {
                System.out.println(2);
            }
        });
        foo.third(new Runnable() {
            @Override
            public void run() {
                System.out.println(3);
            }
        });
    }
    public void first(Runnable printFirst) throws InterruptedException  {
        lock.lock();
        try {
            while (num!=1){
                condition1.await();
            }
            // printFirst.run() outputs "first". Do not change or remove this line.
            printFirst.run();
            condition2.signal();
            num=2;
        }finally {
            lock.unlock();
        }
    }

    public void second(Runnable printSecond) throws InterruptedException {
        lock.lock();
        try {
            while (num!=2){
                condition2.await();
            }
            Thread.sleep(1000);
            // printSecond.run() outputs "second". Do not change or remove this line.
            printSecond.run();
            condition3.signal();
            num=3;
        }finally {
            lock.unlock();
        }
    }

    public void third(Runnable printThird) throws InterruptedException {
        lock.lock();
        try {
            while (num!=3){
                condition3.await();
            }
            // printThird.run() outputs "third". Do not change or remove this line.
            printThird.run();
            condition1.signal();
            num=1;
        }finally {
            lock.unlock();
        }
    }

}